package com.snack.shop.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.shop.common.Result;
import com.snack.shop.entity.Product;
import com.snack.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 商品控制器
 */
@Tag(name = "商品管理")
@RestController
@RequestMapping("/product")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;

    @Operation(summary = "分页查询商品列表")
    @GetMapping("/page")
    public Result<Page<Product>> page(
        @Parameter(description = "分类ID（0表示全部）") @RequestParam(defaultValue = "0") Long categoryId,
        @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer current,
        @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
        @Parameter(description = "商品状态（null查全部，0下架，1上架）") @RequestParam(required = false) Integer status,
        @Parameter(description = "是否库存预警（true时按阈值筛选）") @RequestParam(required = false) Boolean lowStock,
        @Parameter(description = "库存预警阈值（默认10）") @RequestParam(required = false) Integer stockThreshold,
        @Parameter(description = "关键词（按名称/描述模糊搜索）") @RequestParam(required = false) String keyword
    ) {
        Page<Product> page = productService.page(categoryId, current, size, status, lowStock, stockThreshold, keyword);
        return Result.success(page);
    }

    @Operation(summary = "获取商品详情")
    @GetMapping("/{id}")
    public Result<Product> getDetail(@PathVariable Long id) {
        Product product = productService.getDetail(id);
        return Result.success(product);
    }

    @Operation(summary = "保存商品")
    @SaCheckRole("merchant")
    @PostMapping("/save")
    public Result<Void> save(@Validated @RequestBody Product product) {
        productService.save(product);
        return Result.success();
    }

    @Operation(summary = "更新商品状态")
    @SaCheckRole("merchant")
    @PostMapping("/updateStatus")
    public Result<Void> updateStatus(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        Integer status = Integer.valueOf(params.get("status").toString());
        productService.updateStatus(id, status);
        return Result.success();
    }

    @Operation(summary = "删除商品")
    @SaCheckRole("merchant")
    @PostMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        productService.delete(id);
        return Result.success();
    }
}

